package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.CartItemVO;
import com.atguigu.gulimall.cart.vo.CartVO;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @Author baiWT
 * @Description
 * @Date 2022/4/7 14:16
 **/
@Service
public class CartServiceImpl implements CartService {

    private final String CART_PREFIX = "gulimall:cart:";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private ProductFeignService productFeignService;

    @Resource
    private ThreadPoolExecutor executor;

    @Override
    public CartItemVO addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String,Object,Object> cartOps = getCartOps();


        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(res)){
            CartItemVO cartItemVO = new CartItemVO();
            //1、远程查询当前要添加的商品信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(()->{
                R skuInfo = productFeignService.info(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", SkuInfoVo.class);
                cartItemVO.setChecked(true);
                cartItemVO.setCount(num);
                cartItemVO.setSkuImg(data.getSkuDefaultImg());
                cartItemVO.setSkuTitle(data.getSkuTitle());
                cartItemVO.setSkuId(skuId);
                cartItemVO.setPrice(data.getPrice());
            },executor);

            //2、远程查询sku的组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(()->{
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItemVO.setAttrs(values);
            },executor);

            //等待线程执行
            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValues).get();
            //3、商品添加到购物车
            String s = JSON.toJSONString(cartItemVO);
            cartOps.put(String.valueOf(skuId),s);

            return cartItemVO;
        }else {
            CartItemVO cartItemVO = JSON.parseObject(res,CartItemVO.class);
            cartItemVO.setCount(cartItemVO.getCount()+num);
            cartOps.put(String.valueOf(skuId),JSON.toJSONString(cartItemVO));
            return cartItemVO;
        }
    }

    /**
     * 获取购物车项
     * @return
     * @param skuId
     */
    @Override
    public CartItemVO getCartItem(Long skuId) {
        BoundHashOperations<String,Object,Object> cartOps = getCartOps();
        String s = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(s,CartItemVO.class);
    }

    /**
     * 购物车列表
     * @return
     */
    @Override
    public CartVO getCart() throws ExecutionException, InterruptedException {
        CartVO cartVO =new CartVO();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()!=null){
            //登录
            //如果临时购物车还有数据
            List<CartItemVO> cartItemVOS = getCartItemVo(CART_PREFIX+userInfoTo.getUserKey());
            if (cartItemVOS != null){
                //临时购物车有数据，需要合并
                for (CartItemVO vo : cartItemVOS){
                    addToCart(vo.getSkuId(),vo.getCount());
                }
                //清楚临时购物车的数据
                clearCart(CART_PREFIX+userInfoTo.getUserKey());
            }

            //获取登录后的购物车数据【包含合并的临时购物车数据和登陆后的购物车数据】
            List<CartItemVO> cartItem = getCartItemVo(CART_PREFIX+userInfoTo.getUserId());
            cartVO.setItems(cartItem);
        }else{
            //没登录
            List<CartItemVO> cartItemVOS = getCartItemVo(CART_PREFIX+userInfoTo.getUserKey());
            cartVO.setItems(cartItemVOS);
        }
        return cartVO;
    }

    /**
     * 清除购物项
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey){
        stringRedisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, boolean checked) {
        BoundHashOperations<String,Object,Object> hashOps = getCartOps();
        CartItemVO cartItemVO = getCartItem(skuId);
        cartItemVO.setChecked(checked);
        hashOps.put(skuId.toString(),JSON.toJSONString(cartItemVO));
    }

    @Override
    public void change(Long skuId, Integer count) {
        BoundHashOperations<String,Object,Object> hashOps = getCartOps();
        CartItemVO cartItemVO = getCartItem(skuId);
        cartItemVO.setCount(count);
        hashOps.put(skuId.toString(),JSON.toJSONString(cartItemVO));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String,Object,Object> hashOps = getCartOps();
        hashOps.delete(skuId.toString());
    }

    @Override
    public List<CartItemVO> getCurrentUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        }else {
            List<CartItemVO> cartItemVOS = getCartItemVo(CART_PREFIX+userInfoTo.getUserId());
            List<CartItemVO> vos = cartItemVOS.stream().filter(item -> item.getChecked()).map(item->{
                BigDecimal price = productFeignService.getPrice(item.getSkuId());
                item.setPrice(price);
                return item;
            }).collect(Collectors.toList());
            return vos;
        }
    }

    /**
     * 获取到我们要操作的购物车
     * @return
     */
    private BoundHashOperations<String,Object,Object> getCartOps(){
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null){
            cartKey = CART_PREFIX+userInfoTo.getUserId();
        }else {
            cartKey = CART_PREFIX+userInfoTo.getUserKey();
        }
        BoundHashOperations<String,Object,Object> hashOperations = stringRedisTemplate.boundHashOps(cartKey);
        return hashOperations;
    }

    private List<CartItemVO> getCartItemVo(String cartKey){
        BoundHashOperations<String,Object,Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values!=null && values.size()>0){
            List<CartItemVO> collect = values.stream().map(value->{
                String str = (String) value;
                CartItemVO cartItemVO = JSON.parseObject(str,CartItemVO.class);
                return cartItemVO;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }
}
